import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_deer/database/beans/shift/current_shift_entity.dart';
import 'package:flutter_deer/database/beans/get_all_goods_entity.dart';
import 'package:flutter_deer/database/beans/get_all_goods_list.dart';
import 'package:flutter_deer/database/beans/get_config_guns_entity.dart';
import 'package:flutter_deer/database/beans/get_merchant_configer.dart';
import 'package:flutter_deer/database/beans/get_mqtt_info_entity.dart';
import 'package:flutter_deer/database/beans/get_token_entity.dart';
import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/database/beans/get_zero_model_entity.dart';
import 'package:flutter_deer/database/beans/pay_type_model.dart';
import 'package:flutter_deer/database/database_manager.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/home/home_page.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/device_info_plus.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:get/get.dart';

/*
Get.to(widget)	跳转到新页面，保留当前页面在路由栈中	Get.to(NextPage());
Get.toNamed(path)	通过命名路由跳转	Get.toNamed('/second');
Get.off(widget)	跳转并移除当前页面（适用于登录后跳转主页）	Get.off(HomePage());
Get.offAll(widget)	跳转并清空所有历史页面（如支付成功后直接跳转首页）	Get.offAll(HomePage());
*/
class LoginPresenter extends BaseNetProvider {
  var nameController = TextEditingController();
  var passwordController = TextEditingController();
  var snCodeController = TextEditingController();

  var isChecked = false.obs;

  late ObjectIdBox _objectIdBox;

  // canLogin 变为响应式变量
  RxBool canLogin = false.obs;

  void _updateCanLogin() {
    canLogin.value = nameController.value.text.isNotEmpty && passwordController.value.text.isNotEmpty && snCodeController.value.text.isNotEmpty;
  }

  void onCheckedChanged(bool? value) {
    final bool = value == true;
    isChecked.value = bool;
    SpUtil.putBool(Constant.rememberCheck, bool);
  }

  void login() {
    final phone = nameController.text;
    final password = passwordController.text;
    final snCode = snCodeController.text;

    requestNetwork<GetTokenEntity>(
      Method.post,
      url: HttpApi.login,
      params: {
        'productLine': 'SaaS',
        'clientType': 'spj',
        'username': phone,
        'password': password.toMd5,
        'deviceCode': snCode,
      },
      onSuccess: (data) {
        SpUtil.putString(Constant.accessToken, data?.accessToken ?? '');
        SpUtil.putString(Constant.phone, phone);
        SpUtil.putString(Constant.snCode, snCode);
        SpUtil.putString(Constant.rememberPsw, password);
        getUserInfo();
        loopRequestAllGoods(1);
        print(' 登录成功 $data');
      },
      onError: (code, msg) {
        print(' 登录失败 code: $code, msg: $msg');
        // view.loginError(msg);
      },
    );
  }

  void getUserInfo() {
    /// 获取用户信息
    final Future<dynamic> userInfo = requestNetwork<GetUserInfoEntity>(Method.get, url: HttpApi.getUserInfo, onSuccess: (data) {
      // print(' 获取用户信息成功 $data');
      data?.save();
    });

    /// 获取油枪配置
    final Future<dynamic> gunInfo = requestNetwork<List<GetConfigGunsEntity>>(Method.post, url: HttpApi.getOilGunConfig, onSuccess: (data) {
      UserConfigManager.setOilGuns(data!);
      // print(' 获取油枪配置成功 $data');
      // view.loginSuccess();
      // Get.to<void>(const Home());
    });

    /// 获取mqtt信息
    final Future<dynamic> mqttInfo = requestNetwork<GetMqttInfoEntity>(Method.get, url: HttpApi.getMqttInfo, onSuccess: (data) {
      data?.save();
      // print(' 获取mqtt信息成功 $data');
    });

    /// 获取零管模式
    final Future<dynamic> modelInfo = requestNetwork<GetZeroModelEntity>(Method.get, url: HttpApi.getZeroModel, onSuccess: (data) {
      data?.save();
      // print('获取零管模式成功 $data');
    });

    /// 获取支付方式
    final Future<dynamic> payTypeInfo = requestNetwork<List<PayTypeModel>>(Method.get, url: HttpApi.getPayType, onSuccess: (data) {
      // print('获取支付方式成功 $data');
      if (data == null || data.isEmpty) {
        Toast.show("支付方式尚未配置！");
        return;
      }
      // 更新到本地
      PayTypeModel.updateAll(data).then((_) {
        print('支付方式更新成功');
      });
    });

    /// 获取当前班组
    final Future<dynamic> shiftInfo = requestNetwork<CurrentShiftEntity>(
      Method.get,
      url: HttpApi.getMerchantWorkCycle,
      onSuccess: (data) {
        data?.save();
        print(' 获取当前班组成功 dataList: ${data}');
      },
      onError: (code, msg) {
        print(' 获取当前班组失败 code: $code, msg: $msg');
      },
    );

    /// 获取充值额外送配置
    final Future<dynamic> preferentialConfig = requestNetwork<GetMerchantPreferentialConfigEntity>(
      Method.post,
      url: HttpApi.getMerchantPreferentialConfig,
      onSuccess: (data) {
        data?.save();
        print(' 获取充值额外送配置成功 dataList: ${data}');
      },
      onError: (code, msg) {
        print(' 获取充值额外送配置失败 code: $code, msg: $msg');
      },
    );

    Future.wait([userInfo, gunInfo, mqttInfo, modelInfo, payTypeInfo, shiftInfo, preferentialConfig]).then((value) {
      Get.off<void>(() => Home());
    }).catchError((error) {
      print('至少有一个网络请求失败: $error');
    });
  }

  final int pageSize = 1000;

  /// 循环请求所有便利店商品并保存到数据库
  void loopRequestAllGoods(int pageNo) {
    asyncRequestNetwork<GetAllGoodsEntity>(
      Method.post,
      url: HttpApi.getGoodsList,
      isShow: false,
      params: {
        // val goodsStatus: List<String> = arrayListOf("0"),
        'goodsStatus': ['0'],
        'goodsTypes': ['5', '6'],
        'salesChannels': ['2'], //销售渠道 1：积分商城 2 : 便利店
        'mchCode': GetUserInfoEntity.get()?.loginMerchantCode,
        'pageSize': pageSize,
        'pageNo': pageNo,
      },
      onSuccess: (data) {
        if (data?.list != null) {
          // 保存到数据库
          if (pageNo == 1) {
            GetAllGoodsList.deleteAll();
          }
          GetAllGoodsList.saveAll(data!.list!);
          if (data.list!.length == pageSize) {
            loopRequestAllGoods(pageNo + 1);
          }
        }
        print(' 循环请求 pageNo: $pageNo dataList: ${data?.list?.length}');
      },
      onError: (code, msg) {
        print(' 循环请求失败 code: $code, msg: $msg');
      },
    );
  }

  @override
  void onInit() {
    super.onInit();

    _objectIdBox = getIt<ObjectIdBox>();
    _objectIdBox.initStore();

    nameController.text = SpUtil.getString(Constant.phone).nullSafe;
    passwordController.text = SpUtil.getString(Constant.rememberPsw).nullSafe;
    isChecked.value = SpUtil.getBool(Constant.rememberCheck) ?? false;

    nameController.addListener(_updateCanLogin);
    passwordController.addListener(_updateCanLogin);
    snCodeController.addListener(_updateCanLogin);
    _updateCanLogin();

    DeviceUniqueIdUtil.getUniqueId().then((value) {
      print(' 设备唯一标识: ${value?.deviceId}  inProduction：${Constant.inProduction}');
      if (value != null && value.deviceId.isNotEmpty && Constant.inProduction) {
        snCodeController.text = value.deviceId.toMd5;
      } else {
        snCodeController.text = SpUtil.getString(Constant.snCode).nullSafe;
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    _objectIdBox.dispose();
  }
}
